from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import Optional
import hashlib
from datetime import datetime

router = APIRouter()

# 数据模型
class UserLogin(BaseModel):
    """用户登录请求模型"""
    username: str
    password: str

class UserResponse(BaseModel):
    """用户信息响应模型"""
    user_id: int
    username: str
    email: Optional[str] = None
    created_at: Optional[datetime] = None

class UserUpdate(BaseModel):
    """用户信息更新模型"""
    email: Optional[str] = None
    password: Optional[str] = None

# 模拟用户数据库（生产环境应使用真实数据库）
MOCK_USERS = {
    1: {
        "user_id": 1,
        "username": "admin",
        "password": hashlib.md5("admin123".encode()).hexdigest(),
        "email": "admin@example.com",
        "created_at": datetime.now()
    }
}

@router.post("/user/login", response_model=dict)
async def login_user(user_data: UserLogin):
    """用户登录"""
    try:
        # 查找用户（这里使用模拟数据）
        user = None
        for uid, u in MOCK_USERS.items():
            if u["username"] == user_data.username:
                user = u
                break
        
        if not user:
            raise HTTPException(status_code=401, detail="用户名或密码错误")
        
        # 验证密码
        password_hash = hashlib.md5(user_data.password.encode()).hexdigest()
        if user["password"] != password_hash:
            raise HTTPException(status_code=401, detail="用户名或密码错误")
        
        return {
            "status": "success",
            "message": "登录成功",
            "user_id": user["user_id"],
            "username": user["username"]
        }
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"登录失败: {str(e)}")

@router.post("/user/logout")
async def logout_user():
    """用户登出"""
    return {
        "status": "success",
        "message": "登出成功"
    }

@router.get("/user/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
    """获取用户信息"""
    try:
        if user_id not in MOCK_USERS:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        user = MOCK_USERS[user_id]
        return UserResponse(
            user_id=user["user_id"],
            username=user["username"],
            email=user["email"],
            created_at=user["created_at"]
        )
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取用户信息失败: {str(e)}")

@router.put("/user/{user_id}")
async def update_user(user_id: int, user_update: UserUpdate):
    """更新用户信息"""
    try:
        if user_id not in MOCK_USERS:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        user = MOCK_USERS[user_id]
        
        if user_update.email is not None:
            user["email"] = user_update.email
        
        if user_update.password is not None:
            user["password"] = hashlib.md5(user_update.password.encode()).hexdigest()
        
        return {
            "status": "success",
            "message": "用户信息更新成功",
            "user_id": user_id
        }
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新用户信息失败: {str(e)}")

@router.get("/user/test")
async def test_user_api():
    """测试用户管理API"""
    return {
        "message": "用户管理API正常运行",
        "endpoints": [
            "POST /api/user/login - 用户登录",
            "POST /api/user/logout - 用户登出", 
            "GET /api/user/{user_id} - 获取用户信息",
            "PUT /api/user/{user_id} - 更新用户信息"
        ],
        "status": "healthy"
    }